var mainPanel;
var topNCombobox;
var categoryCombobox;
var dailyStroe;
var weekStroe;
var monthStroe;
var quarterStroe;
var tabPanelChanged = false;
var siteDs;

if (Ext.isIE) {
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-date-trigger { margin-top:-1px  } </style>');
	document
			.write('<style type="text/css">.x-form-field-wrap .x-form-trigger { margin-top:-1px  } </style>');
}

function getTopNCombox() {
	var store = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '10', '10名' ], [ '20', '20名' ], [ '50', '50名' ] ]
	});

	var combobox = new Ext.form.ComboBox({
		id : 'topNComboBox',
		store : store,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	combobox.on('select', function(combo, record) {
		reLoadData();
	});

	// sets default value
	var firstValue = store.getRange()[0].data.value;
	combobox.setValue(firstValue);

	return combobox;
}

function getCategoryCombox() {
	var store = new Ext.data.SimpleStore({
		fields : [ 'value', 'description' ],
		data : [ [ '全部', '全部' ], [ '电影', '电影' ], [ '电视剧', '电视剧' ],
				[ '少儿', '少儿' ], [ '新闻', '新闻' ], [ '体育', '体育' ], [ '凤凰', '凤凰' ],
				[ '娱乐', '娱乐' ], [ '时尚生活', '时尚生活' ], [ '法治', '法治' ],
				[ '纪实', '纪实' ], [ '财经', '财经' ], [ '音乐', '音乐' ] ]
	});

	var combobox = new Ext.form.ComboBox({
		id : 'categoryNComboBox',
		fieldLabel : "节目分类 ",
		store : store,
		displayField : 'description',
		forceSelection : true,
		valueField : 'value',
		mode : 'local',
		width : 60,
		editable : false,
		lazyInit : false,
		selectOnFocus : true,
		triggerAction : 'all',
		triggerClass : 'x-form-trigger2'
	});

	combobox.on('select', function(combo, record) {
		reLoadData();
	});

	// sets default value
	var firstValue = store.getRange()[0].data.value;
	combobox.setValue(firstValue);

	return combobox;
}

function tabChange() {
	if (!tabPanelChanged) {
		tabPanelChanged = true;
	} else {
		reLoadData();
	}
}

function reLoadData() {
	if (mainPanel) {
		var ds;
		var type;
		if (mainPanel.activeTab.id == 'dailyPanel') {
			ds = dailyStroe;
			type = 'daily';
		} else if (mainPanel.activeTab.id == 'weekPanel') {
			ds = weekStroe;
			type = 'weekly';
		} else if (mainPanel.activeTab.id == 'monthPanel') {
			ds = monthStroe;
			type = 'monthly';
		} else {
			ds = quarterStroe;
			type = 'quarter';
		}

		var category = categoryCombobox.getValue();
		var topN = topNCombobox.getValue();

		ds.baseParams = {
			cmd : 'info',
			action : 'geTopNInfosToJSON'
		};
		ds
				.load({
					params : {
						type : type,
						topN : topN,
						category : category,
						siteCode : BestvSearch.sc,
						increase : true
					},
					callback : function(r, options, success) {
						if (r.length == 0) {
							if (success) {
								Ext.MessageBox.alert(TXT_common_hint,
										TXT_search_empty_msg);
								return;
							} else {
								if (ds.reader.responseText == '[null]') {
									Ext.Msg
											.alert(
													TXT_common_hint,
													TXT_common_relogin,
													function() {
														window.location.href = '../eni/common/logout.jsp';
													});
									return;
								} else {
									Ext.MessageBox.alert(TXT_common_hint,
											TXT_SITE_CONFIGURATION_CHECK);
									return;
								}
							}
						}
					}
				});
	}
}

function getDataStroe(type, topN, siteCode, category) {
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			fields : [ {
				name : 'index',
				type : 'int'
			}, {
				name : 'name'
			}, {
				name : 'code'
			}, {
				name : 'category'
			}, {
				name : 'infoFlag'
			}, {
				name : 'count'
			}, {
				name : 'increaseNo'
			} ]
		})
	});

	ds.baseParams = {
		cmd : 'info',
		action : 'geTopNInfosToJSON'
	};
	ds
			.load({
				params : {
					type : type,
					topN : topN,
					category : category,
					siteCode : BestvSearch.sc,
					increase : true
				},
				callback : function(r, options, success) {
					if (r.length == 0) {
						if (success) {
							Ext.MessageBox.alert(TXT_common_hint,
									TXT_search_empty_msg);
							return;
						} else {
							if (ds.reader.responseText == '[null]') {
								Ext.Msg
										.alert(
												TXT_common_hint,
												TXT_common_relogin,
												function() {
													window.location.href = '../eni/common/logout.jsp';
												});
								return;
							} else {
								Ext.MessageBox.alert(TXT_common_hint,
										TXT_SITE_CONFIGURATION_CHECK);
								return;
							}
						}
					}
				}
			});

	return ds;
}

function getInfoLeaderBoardGrid(dataStroe, type) {
	var keyCm = new Ext.grid.ColumnModel([ {
		header : TXT_search_leaderboard_no_label,
		dataIndex : 'index',
		width : 100
	}, {
		header : TXT_vod_name,
		dataIndex : 'name',
		width : 300
	}, {
		header : 'code',
		dataIndex : 'code',
		width : 240
	}, {
		header : 'category',
		dataIndex : 'category',
		width : 120
	}, {
		header : TXT_vod_is_Header,
		dataIndex : 'infoFlag',
		width : 150
	}, {
		header : TXT_vod_hit_count,
		dataIndex : 'count',
		width : 100
	}, {
		header : TXT_vod_increase_count,
		dataIndex : 'increaseNo',
		width : 100
	} ]);

	var keySm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});

	var keyGrid = new Ext.grid.GridPanel({
		border : false,
		region : 'center',
		ds : dataStroe,
		cm : keyCm,
		sm : keySm,
		stripeRows : true,
		autoHeight : true,
		loadMask : {
			msg : 'key loading..'
		}
	});

	return keyGrid;
}

function exportExcelButtonClick() {
	if (!BestvSearch.isSessionTimeOut()) {
		var topN = topNCombobox.getValue();

		var siteCode = BestvSearch.sc;
		if (!siteCode)
			siteCode = "";

		window.location.href = '../DispatchServlet?cmd=info&action=createExcel&expExcel=y&topN='
				+ topN
				+ '&increase=true&siteCode='
				+ siteCode
				+ '&flag='
				+ Math.random();
	} else {
		Ext.Msg.alert(TXT_common_hint, TXT_common_relogin, function() {
			window.location.href = '../eni/common/logout.jsp';
		});
	}
}

function displayLeaderBoard() {
	topNCombobox = getTopNCombox();
	var topN = topNCombobox.getValue();

	categoryCombobox = getCategoryCombox();
	var category = categoryCombobox.getValue();

	var siteCode = BestvSearch.sc;
	if (!siteCode)
		siteCode = "";

	dailyStroe = getDataStroe('daily', topN, siteCode, category);
	// Just get daily dataStore, so that, just need send one request to server,
	// For others dataStore, use dailyStore instead when init, and also will be
	// updated when tab changed.
	weekStroe = dailyStroe;
	monthStroe = dailyStroe;
	quarterStroe = dailyStroe;

	var dailyGird = getInfoLeaderBoardGrid(dailyStroe, 'daily');
	var weekGird = getInfoLeaderBoardGrid(weekStroe, 'weekly');
	var monthGird = getInfoLeaderBoardGrid(monthStroe, 'monthly');
	var quarterGird = getInfoLeaderBoardGrid(quarterStroe, 'quarter');

	var exportExcelButton = new Ext.Button({
		id : "exportExcelButton",
		text : TXT_search_export_excel_text,
		type : "button",
		handler : exportExcelButtonClick
	});

	mainPanel = new Ext.TabPanel({
		region : 'center',
		activeTab : 0,
		frame : true,
		buttonAlign : 'right',
		layoutOnTabChange : true,
		margins : '0,20,0,0',
		tbar : [ '-', exportExcelButton, '-', '->', categoryCombobox, '-',
				'&nbsp;&nbsp;&nbsp;&nbsp;前', '-', topNCombobox, '-' ],
		listeners : {
			'tabchange' : tabChange
		},
		items : [ {
			id : 'dailyPanel',
			title : TXT_search_leaderboard_daily_label,
			closable : false,
			autoScroll : true,
			height : 500,
			items : [ dailyGird ]
		}, {
			id : 'weekPanel',
			title : TXT_search_leaderboard_week_label,
			closable : false,
			autoScroll : true,
			items : [ weekGird ]
		}, {
			id : 'monthPanel',
			title : TXT_search_leaderboard_month_label,
			closable : false,
			autoScroll : true,
			items : [ monthGird ]
		}, {
			id : 'quarterPanel',
			title : TXT_search_leaderboard_quarer_label,
			closable : false,
			autoScroll : true,
			items : [ quarterGird ]
		} ]
	});

	BestvSearch.glb_mainPanel.add(mainPanel);
	BestvSearch.drawMainFrame(
			TXT_app_name + '-' + TXT_search_leaderboard_label, siteDs);
}

Ext.onReady(displayLeaderBoard);